from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys#键盘操作的库
import time
def spider(url,keyword):
    driver=webdriver.Chrome()
    driver.get(url)
    driver.implicitly_wait(3)#隐式等待
    get_goods(driver)
    try:
        input_tag=driver.find_element_by_id('key')
        input_tag.send_keys(keyword)
        input_tag.send_keys(Keys.ENTER)#回车键
        time.sleep(10)#停顿5秒
    finally:
        time.sleep(10)
def get_goods(driver):
    try:
        driver.implicitly_wait(10)
        time.sleep(10)
        goods=driver.find_elements_by_class_name('gl-item')#定位到每一个商品
        #goods=driver.find_elements_by_xpath('')
        print(goods)
        for good in goods:
            detail_url=good.find_element_by_tag_name('a').get_attribute('href')                       #class="p-name p-name-type-2"
            p_name=good.find_element_by_css_selector('.p-name  em').text.replace('\n','')#. 用class命名用'.' ID 用'#'
            price=driver.find_element_by_css_selector('.p-price i').text#i为下级标签
            p_comment=driver.find_element_by_css_selector('.p-commit a').text
            print(p_name,detail_url,price,p_comment)
            msg='''
            商品:%s
            链接:%s
            价格:%s
            评论:%s
            '''%(p_name,detail_url,price,p_comment)
            print(msg)
    except Exception as e:
        print(e)




if __name__=='__main__':


    spider('https://www.jd.com/',keyword='口罩')
    print(1)

